// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, TextInput, PermissionsAndroid } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/Ionicons';
import ImagePicker from 'react-native-image-crop-picker';

// antd 按需加载
import { Tabs, Toast, Portal } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { modify, getUser } from '../../module/module.js'
import * as ActionTypes from '../../constants/constants.js';

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, CacheImage, Layout } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { size, ScreenWidth, FileUpload } from '../../util/utils.js'

class UpdataUser extends Component {

  constructor(props) {
    super(props)
    this.state = {
      headImg: '',
      nickName: '',
      signature: ''
    }
  }


  async requestCameraPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        {
          'title': '需要访问相册',
          'message': '上传头像需要该权限',
        },
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        this.setState({
          avatarPermiss: true,
        })
      } else {
        this.setState({
          avatarPermiss: false,
        })
      }
    } catch (err) {
      console.warn(err)
    }
  }

  handleModify() {
    const { userInfo, changeType } = this.props
    const { headImg, nickName, signature, } = this.state
    let option = {
      id: userInfo.id
    }
    if (changeType == 'headImg') {
      option['headImg'] = headImg
    }
    if (changeType == 'nickName') {
      option['nickName'] = nickName
    }
    if (changeType == 'signature') {
      option['signature'] = signature
    }
    modify(option).then(res => {
      if (res) {
        getUser()
        Actions.pop()
      }
    }).finally(() => {

    })
  }

  pickBase64Phone() {
    const { userInfo } = this.props
    ImagePicker.openPicker({
      width: 400,
      height: 400,
      cropping: true,
      includeBase64: true,
    }).then(image => {
      console.log(image)
      this.setState({
        headImg: `data:${image.mime};base64,${image.data}`
      })

      // let id = new Date().getTime()
      // let formData = new FormData();
      // formData.append('id', id)
      // formData.append('file', { uri: 'file://' + image.path, type: 'multipart/form-data' })
      // upload(formData).then(res => {
      //   console.log(res)
      // }).catch(error => {
      //   console.log(error)
      // })

      FileUpload(userInfo.id, image).then(res => {
        console.log(res, '上传结果')
        getUser()
        Actions.pop()
      }).catch(error => {
        Toast.info('上传失败', 2)
        console.log(error, '上传失败')
      })
    }).catch(e => {
    });
  }

  render() {
    const { userInfo, changeType, } = this.props
    const { headImg } = this.state
    let title = ''
    if (changeType == 'headImg') { title = '修改头像' }
    if (changeType == 'nickName') { title = '修改昵称' }
    if (changeType == 'signature') { title = '修改个性签名' }
    return (
      <Layout style={{ backgroundColor: '#0A0C21' }} statusStyle={{}}>
        <NavBar
          type="transparent"
          title={title}
          back={true}
        />
        <ScrollView style={Style.content}>
          <View style={{ paddingHorizontal: 16, }}>
            {changeType == 'headImg' && (
              <View style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 20 }}>
                <View style={{ marginRight: 10 }}><Text style={{ fontSize: 14, color: '#fff', lineHeight: 20, }}>头像</Text></View>
                <View style={{ flex: 1 }}>
                  <TouchableOpacity
                    onPress={() => this.pickBase64Phone()}
                  >
                    {headImg ?
                      <Image resizeMode='cover' style={{ width: 88, height: 88, borderWidth: 1, borderColor: '#eee' }} source={{ uri: headImg }} />
                      :
                      <View style={{ backgroundColor: '#fff', width: 88, height: 88, borderWidth: 1, borderColor: '#eee', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }}>
                        <Text style={{ fontSize: 40, color: '#fff', lineHeight: 88, }}>+</Text>
                      </View>
                    }
                  </TouchableOpacity>
                </View>
              </View>
            )}

            {changeType == 'nickName' && (
              <View style={{ flexDirection: 'row', alignItems: 'center', height: 60, }}>
                <View style={{ marginRight: 10 }}><Text style={{ fontSize: 14, color: '#fff', lineHeight: 20, }}>昵称</Text></View>
                <View style={{ flex: 1 }}>
                  <TextInput
                    onChangeText={(nickName) => this.setState({ nickName })}
                    defaultValue={userInfo.nickName}
                    placeholder="请输入昵称"
                    placeholderTextColor="#8A90A8"
                    style={{
                      flex: 1,
                      fontSize: 14,
                      borderWidth: 0,
                      color: '#fff',
                    }}
                    underlineColorAndroid="transparent"
                  />
                </View>
              </View>
            )}

            {changeType == 'signature' && (
              <View style={{ flexDirection: 'row', alignItems: 'center', height: 60, }}>
                <View style={{ marginRight: 10 }}><Text style={{ fontSize: 14, color: '#fff', lineHeight: 20, }}>个性签名</Text></View>
                <View style={{ flex: 1 }}>
                  <TextInput
                    onChangeText={(signature) => this.setState({ signature })}
                    defaultValue={userInfo.signature}
                    placeholder="请输入个性签名"
                    placeholderTextColor="#8A90A8"
                    style={{
                      flex: 1,
                      fontSize: 14,
                      borderWidth: 0,
                      color: '#fff',
                    }}
                    underlineColorAndroid="transparent"
                  />
                </View>
              </View>
            )}
            <View style={{ height: .5, backgroundColor: '#232B54' }} />
          </View>

          <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingHorizontal: 40, paddingVertical: 30 }}>
            <TouchableOpacity
              onPress={() => {
                this.handleModify()
              }}
              style={{
                flex: 1,
                height: 40,
                backgroundColor: '#7484FF',
                borderRadius: 4,
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <Text style={{ fontSize: 16, color: '#fff', lineHeight: 20, }}>确认修改</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </Layout>
    );
  }
}


export default connect(({ userInfo }) => ({
  userInfo,
}))(pureRender(UpdataUser))
